#include "RingQueue.hpp"
#include "Task.hpp"
#include "unistd.h"
#include <pthread.h>

void *Producer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (true)
    {
        // 构造/生产数据--工厂
        int a = rand() % 10 + 1; //[1, 10]
        int b = rand() % 10 + 1;
        Task t(a, b);
        // 生产数据--商店角度；发送数据--工厂角度
        rq->Push(&t);
        std::cout << "push ";
        t.Debug();
        sleep(1);
    }

    return nullptr;
}
void *Consumer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (true)
    {
        // 1.消费
        Task t; // 为输出型参数提前开辟空间
        rq->Pop(&t);
        std::cout << "pop ";
        // 2.处理数据
        t.Execute();
        t.Result();
    }

    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task> rq(5);
    pthread_t p_id1;
    pthread_t p_id2;
    std::string nameProducer = "Producer";
    pthread_create(&p_id1, nullptr, Producer, &rq); //(void *)nameProducer.c_str()
    pthread_create(&p_id2, nullptr, Producer, &rq);

    sleep(1);

    pthread_t c_id1;
    pthread_t c_id2;
    pthread_t c_id3;
    std::string nameConsumer = "Consumer";
    pthread_create(&c_id1, nullptr, Consumer, &rq); //(void *)nameConsumer.c_str()
    pthread_create(&c_id2, nullptr, Consumer, &rq);
    pthread_create(&c_id3, nullptr, Consumer, &rq);

    pthread_join(p_id1, nullptr);
    pthread_join(p_id2, nullptr);
    pthread_join(c_id1, nullptr);
    pthread_join(c_id2, nullptr);
    pthread_join(c_id3, nullptr);

    return 0;
}